get.ts 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { createRoute, OpenAPIHono } from '@hono/zod-openapi';
  2. import { UserService } from '@/server/modules/users/user.service';
  3. import { z } from '@hono/zod-openapi';
  4. import { authMiddleware } from '@/server/middleware/auth.middleware';
  5. import { ErrorSchema } from '@/server/utils/errorHandler';
  6. import { AppDataSource } from '@/server/data-source';
  7. import { AuthContext } from '@/server/types/context';
  8. import { UserResponseSchema } from '@/server/modules/users/user.schema';
  9. import { parseWithAwait } from '@/server/utils/parseWithAwait';
  10. const userService = new UserService(AppDataSource);
  11. const GetParams = z.object({
  12. id: z.coerce.number().openapi({
  13. param: { name: 'id', in: 'path' },
  14. example: 1,
  15. description: '用户ID'
  16. })
  17. });
  18. const routeDef = createRoute({
  19. method: 'get',
  20. path: '/{id}',
  21. middleware: [authMiddleware],
  22. request: {
  23. params: GetParams
  24. },
  25. responses: {
  26. 200: {
  27. description: '成功获取用户详情',
  28. content: { 'application/json': { schema: UserResponseSchema } }
  29. },
  30. 404: {
  31. description: '用户不存在',
  32. content: { 'application/json': { schema: ErrorSchema } }
  33. },
  34. 500: {
  35. description: '服务器错误',
  36. content: { 'application/json': { schema: ErrorSchema } }
  37. }
  38. }
  39. });
  40. const app = new OpenAPIHono<AuthContext>().openapi(routeDef, async (c) => {
  41. try {
  42. const { id } = c.req.valid('param');
  43. const user = await userService.getUserById(id);
  44. if (!user) {
  45. return c.json({ code: 404, message: '用户不存在' }, 404);
  46. }
  47. return c.json(await parseWithAwait(UserResponseSchema, user), 200);
  48. } catch (error) {
  49. return c.json({
  50. code: 500,
  51. message: error instanceof Error ? error.message : '获取用户详情失败'
  52. }, 500);
  53. }
  54. });
  55. export default app;